﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessObjects;
using System.Collections.ObjectModel;
using System.Data.Services.Client;
using TcpServer.GreenWorldEntitiesService;

namespace YourWorldServer
{
    public class RubbishBinsRepository
    {
        private GreenWorldEntities entities;

        private static RubbishBinsRepository instance;

        public RubbishBinsRepository()
        {
            this.entities = new GreenWorldEntities( new Uri( ServiceUrl, UriKind.Absolute ) );
        }
        
        public static string ServiceUrl
        {
            get;
            set;
        }

        public static RubbishBinsRepository Instance
        {
            get
            {
                if ( instance == null )
                    instance = new RubbishBinsRepository();

                return instance;
            }
        }

        public ObservableCollection<Bin> MapBinsCollection
        {
            get;
            private set;
        }

        public void Initialize()
        {
            this.MapBinsCollection = new ObservableCollection<Bin>();
          //  this.LoadBinsCollection();
        }

        public void ClearValues()
        {
            foreach ( Bin bin in this.MapBinsCollection )
                bin.ContentItems.Clear();
        }

        public void AddRubbsihToBin( Rubbish rubbish, int binId )
        {
            Bin bin = this.MapBinsCollection.Where( x => x.MaterialId == binId ).FirstOrDefault();

            //Debug.Assert( bin != null, "Bin not found!" );

            bin.ContentItems.Add( rubbish );
        }

        private void LoadBinsCollection()
        {
            var materialTypes = ( from r in entities.Materials select r ) as DataServiceQuery<Material>;
            materialTypes.BeginExecute( new AsyncCallback( this.LoadMaterialTypesCompleted ), materialTypes );
        }

        private void LoadMaterialTypesCompleted( IAsyncResult state )
        {
            var materialTypes = state.AsyncState as DataServiceQuery<Material>;

            List<Material> ros = materialTypes.EndExecute( state ).ToList();

            foreach ( Material material in ros )
            {
                if ( material.Type == Consts.UnSpecifiedBinType )
                    continue;

                Bin bin = new Bin()
                {
                    Name = material.Type,
                    MaterialId = material.Id
                };

                this.MapBinsCollection.Add( bin );
            }
        }
    }
}
